package com.example.chapter3.controller;

import com.example.chapter3.entity.User;
import com.example.chapter3.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Slf4j
@Controller
public class UserController { // 修改类名为UserController
    @Autowired
    private UserService userService;

    @RequestMapping(value = {"/index", "/main"}, method = RequestMethod.POST)
    public String index() {
        log.info("打开主页");
        return "forward:index.html";
    }

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        log.info("跳转登录界面");
        return "login";
    }

    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public ModelAndView showregister() {
        ModelAndView modelAndView = new ModelAndView();
        User user = new User();
        modelAndView.addObject("user", user);
        modelAndView.setViewName("register");
        return modelAndView;
    }

    @RequestMapping(value = "/userlogin", method = RequestMethod.POST) // 修改为POST请求
    @ResponseBody
    public ModelAndView userlogin(ModelAndView mv, User user) {
        log.info("用户名: " + user.getUsername() + ", 密码: " + user.getPassword());
        if (userService.login(user.getUsername(), user.getPassword())) {
            mv.setViewName("index");
            mv.addObject("user", user);
        } else {
            mv.setViewName("login");
            mv.addObject("error", "登录失败");
        }
        return mv;
    }
}